package alexAI;

import alexAI.*;

//ref: http://www.cs.unm.edu/~aaron/downloads/qian_search.pdf page 5and6

public class HeuristicAlphaBeta {
	private int score;      		 //value of the move
	private int[][] move;  			 //current board position
	private int d; 					 //search depth
	private int alpha = -1000000000; /*lower bound of expected value of 
									   the tree start with -infinite*/
	private int beta = 1000000000;   /*upper bound of expected value of 
									   the tree start with infinite*/
	private HistoryTable table;
	
	private int[][] bestMove;
	
	
	//constant for player is white or black
	private final static boolean white = true;
	private final static boolean black = false;
	
	
	//search game tree to given depth and return evaluation of root
	public int alphaBeta(int[][] move, int d, int alpha, int beta, boolean min, Board b){
		this.d = d;
		if (this.d == 0 || !(b.checkForWinner(move) == 0))
			return b.evalMove(move);
		if(min){
			int[] rating = new int[b.getAllValidMoves(min).size()];
			score = -1000000000;		//evaluate leaf position from current player's standpoint
			for (int i = 0; i < b.getAllValidMoves(min).size(); i++)
				rating[i] = b.evalMove(b.getAllValidMoves(min).get(i));
			//sort(move, rating);      //sorting moves according to their history scores
			for (int i = 0;i < b.getAllValidMoves(min).size(); i++){
				b.updateBoard(b.getAllValidMoves(min).get(i));  //excute current move and update board
				int cur = 0 - alphaBeta(b.getAllValidMoves(min).get(i), d-1, beta, alpha ,!min, b);
				if(cur > score){		//compare returnded value and score value, note new best score if neccssary
					score = cur;
					bestMove = b.getAllValidMoves(min).get(i);
				}
				if (score > alpha)
					score = alpha;
				if (alpha >= beta){
					done();
					break;
				}
			}



		}
		return (Integer) null;
	}
	
	private int done(){
		table.addMoveHistory(bestMove, d);
		return table.length();
	}
	
}
